import React, { useState } from 'react';
import { Select, Modal, Row, Col, Card, Input } from 'antd';
import { IconMap } from '@/providers/router-provider/resources';

const { Search } = Input;

interface IconSelectorProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
}

export const IconSelector: React.FC<IconSelectorProps> = ({ 
  value, 
  onChange, 
  placeholder = "请选择图标" 
}) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');

  // 获取所有图标名称
  const iconNames = Object.keys(IconMap);
  
  // 过滤图标
  const filteredIcons = iconNames.filter(name => 
    name.toLowerCase().includes(searchText.toLowerCase())
  );

  const handleIconSelect = (iconName: string) => {
    onChange?.(iconName);
    setIsModalVisible(false);
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setSearchText('');
  };

  return (
    <>
      <Select
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        onClick={showModal}
        open={false}
        style={{ width: '100%' }}
        suffixIcon={
          value ? (
            <span style={{ fontSize: '16px' }}>
              {
                IconMap[value as keyof typeof IconMap] ? React.cloneElement(IconMap[value as keyof typeof IconMap], {}) : value
              }
            </span>
          ) : null
        }
      />
      
      <Modal
        title="选择图标"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={800}
        bodyStyle={{ maxHeight: '500px', overflow: 'auto' }}
      >
        <Search
          placeholder="搜索图标"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ marginBottom: 16 }}
        />
        
        <Row gutter={[8, 8]}>
          {filteredIcons.map((iconName) => (
            <Col span={6} key={iconName}>
              <Card
                hoverable
                size="small"
                onClick={() => handleIconSelect(iconName)}
                style={{
                  textAlign: 'center',
                  cursor: 'pointer',
                  border: value === iconName ? '2px solid #1890ff' : '1px solid #d9d9d9'
                }}
              >
                <div style={{ fontSize: '24px', marginBottom: '8px' }}>
                  {React.cloneElement(IconMap[iconName as keyof typeof IconMap], {})}
                </div>
                <div style={{ fontSize: '12px', color: '#666' }}>
                  {iconName}
                </div>
              </Card>
            </Col>
          ))}
        </Row>
        
        {filteredIcons.length === 0 && (
          <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
            未找到匹配的图标
          </div>
        )}
      </Modal>
    </>
  );
}; 